<?php

$product = new Product($product_id);

if (isset($_REQUEST['line']) and is_numeric($_REQUEST['line'])) {
	$line = $db->fetchRow("SELECT * FROM shop_baskets_lines WHERE id=?", $_REQUEST['line']);
	$line['attributes'] = $db->fetchAll("SELECT attribute_id, value FROM shop_products_attributes_values WHERE product_id=?", $line['product_id']);
	$line['simpleattributes'] = $db->fetchAll("SELECT simpleattribute_id, value FROM shop_baskets_lines_simpleattributes WHERE line_id=?", $line['id']);
	#print_r($line);
	#exit;
	$product->setQuantity($line['quantity']);
	foreach($line['attributes'] as $attribute) {
		$product->setAttribute($attribute['attribute_id'], $attribute['value']);
	}
	foreach($line['simpleattributes'] as $attribute) {
		$product->setSimpleAttribute($attribute['simpleattribute_id'], $attribute['value']);
	}
	
}

if ($_POST) {
	$product->setQuantity($_POST['quantity']);
	if (isset($_POST['attributes'])) foreach($_POST['attributes'] as $id => $val) {
		$product->setAttribute($id, $val);
	}
	if (isset($_POST['simpleattributes'])) foreach($_POST['simpleattributes'] as $id => $val) {
		$product->setSimpleAttribute($id, $val);
	}
}

$smarty->assign('product', $product->export(true));

if (isset($_POST['add-to-basket'])) {
	
	// replacing line
	if (is_numeric($_POST['line'])) {
		$basket->del($_POST['line']);
	}
	
	$line_id = $basket->add($product);
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		$basket = new Basket();
		$smarty->assign('basket', $basket->export());
		header('Content-type: text/xml');
		$smarty->display('shop/add-to-basket.tpl.taconite');
	} else {
		header('Location: ' . $page['full_path'] . 'basket/');
		exit;
	}
} else {
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display(isset($_REQUEST['quickview']) ? 'shop/quickview.tpl.taconite' : 'shop/product.tpl.taconite');
	} else {
		$smarty->display(isset($_REQUEST['quickview']) ? 'shop/quickview.tpl.html' : 'shop/product.tpl.html');
	}
}
